﻿using UnityEngine;
using System.Collections;

public class ElementManager : MonoBehaviour {
    public enum GameSize {
        extraSmall = 1,
        small = 2,
        normal = 3,
        big = 4,
        extraBig = 5
    }
    GameSize m_curSize = GameSize.normal;

    public GameObject ElementClone = null;

    float c_btnWidth = 120;
    float c_btnHeight = 50;
    float c_btnDis = 60;
    static int s_sizeScale = 5;
    static float s_probability = 0.11f;

    Vector3 SceneOffset = new Vector3( -( s_sizeScale * 1.0f / 2 ), -( s_sizeScale * 1.0f / 2 ), 0 );
	
    void Start() {
        SetSize( m_curSize );
        CreatGame();
    }

    private void CreatGame() {
        if ( ElementClone != null ) {
            ElementClone.transform.localPosition = new Vector3( 1000, 1000, 0 );

            ClearOld();

            transform.localPosition = SceneOffset * (int)m_curSize;
            Grid.Elements = new Element[Grid.W, Grid.H];
            for ( int i = 0; i < Grid.W; ++i ) {
                for ( int j = 0; j < Grid.H; ++j ) {
                    var go = Instantiate( ElementClone ) as GameObject;
                    go.transform.parent = this.transform;
                    go.transform.localPosition = new Vector3( i, j, 10 );
                    var element = go.GetComponent<Element>();
                    element.IsMine = Random.value < s_probability;
                    Grid.Elements[i, j] = element;
                }
            }
        }
    }

    private void ClearOld() {
        var parent = transform;
        if ( parent.childCount > 0 ) {
            for ( int i = parent.childCount - 1; i >= 0; --i ) {
                Destroy( parent.GetChild( i ).gameObject );
            }
        }
    }

    void OnGUI() {
        if ( GUI.Button( new Rect( 10, 10 + c_btnDis, c_btnWidth, c_btnHeight ), "size 1" ) ) {
            SetSize( GameSize.extraSmall );
            CreatGame();
        }
        if ( GUI.Button( new Rect( 10, 10 + c_btnDis * 2, c_btnWidth, c_btnHeight ), "size 2" ) ) {
            SetSize( GameSize.small );
            CreatGame();
        }
        if ( GUI.Button( new Rect( 10, 10 + c_btnDis * 3, c_btnWidth, c_btnHeight ), "size 3" ) ) {
            SetSize( GameSize.normal );
            CreatGame();
        }
        if ( GUI.Button( new Rect( 10, 10 + c_btnDis * 4, c_btnWidth, c_btnHeight ), "size 4" ) ) {
            SetSize( GameSize.big );
            CreatGame();
        }
        if ( GUI.Button( new Rect( 10, 10 + c_btnDis * 5, c_btnWidth, c_btnHeight ), "size 5" ) ) {
            SetSize( GameSize.extraBig );
            CreatGame();
        }
    }

    void SetSize( GameSize size ) {
        Grid.SetWidthHight( s_sizeScale * (int)size, s_sizeScale * (int)size );
        m_curSize = size;
    }
}
